package com.ruoyi.ruonorder.service.impl;

import java.math.BigDecimal;
import java.util.List;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.ruonorder.utils.DistanceUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.ruonorder.mapper.OrderInfoMapper;
import com.ruoyi.ruonorder.domain.OrderInfo;
import com.ruoyi.ruonorder.service.IOrderInfoService;

/**
 * 抢单功能Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-08-22
 */
@Service
public class OrderInfoServiceImpl implements IOrderInfoService 
{
    @Autowired
    private OrderInfoMapper orderInfoMapper;




    @Override
    public AjaxResult assignOrder(Long id) {
        //先去查询订单信息,查询司机和乘客距离3公里的信息,放到抢单大厅里面
        OrderInfo orderInfo = orderInfoMapper.getById(id);
        //获取到司机的经纬度,乘客的经纬度
        double receiveOrderCarLongitude = orderInfo.getReceiveOrderCarLongitude();
        double receiveOrderCarLatitude = orderInfo.getReceiveOrderCarLatitude();
        double depLatitude = orderInfo.getDepLatitude();
        double depLongitude = orderInfo.getDepLongitude();
        BigDecimal distance = BigDecimal.valueOf(DistanceUtils.haversineDistance(receiveOrderCarLatitude, receiveOrderCarLongitude, depLatitude, depLongitude));
        //检查乘客和司机的距离是否超过三公里
        if (distance.compareTo(BigDecimal.valueOf(3)) > 0){
            //查询待接单的订单
           List<OrderInfo> order = orderInfoMapper.selectOnePendingOrder();
            for (OrderInfo info : order) {
                if (info == null) {
                    //如果没有找到待接单的订单,就返回信息
                    return AjaxResult.error("现在还没有订单");
                }
                //有待接单的订单,更新订单状态,将其分配给司机
                int updateCount = orderInfoMapper.updateOrderDriverIdAndStatus(info.getId());
                if (updateCount>0){
                    return AjaxResult.success("接单成功");
                }
            }
        }
        return AjaxResult.success("没有符合的订单");
    }
}
